<template>
  <div class="user_box">
    <div class="user_login">
      <div class="error">{{ message }}</div>
      <form>
        <div class="label">
          <input
            type="text"
            placeholder="请输入用户名"
            name="username"
            v-model.trim="username"
          /><br />
          <input
            type="password"
            placeholder="请输入密码"
            name="password"
            v-model.trim="password"
          /><br />
        </div>
        <div class="submit">
          <input type="submit" value="登录" @click.prevent="login" />
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
export default {
  name: "UserLogin",
  data() {
    return {
      username: "",
      password: "",
      message: "",
    };
  },
  methods: {
    checkFrom() {
      if (!this.username || !this.password) {
        this.message("用户名或密码不能为空");
        return false;
      }
      return true;
    },
    ...mapMutations("user", ["saveUser"]),
    login() {
      this.message = "";
      if (!this.checkFrom()) {
        return false;
      }
      this.axios
        .post("/login", {
          username: this.username,
          password: this.password,
        })
        .then((res) => {
          if (res.status == 200) {
              console.log();
            this.saveUser(JSON.parse(res.config.data));
            this.username = "";
            this.password = "";

            console.log(this);
            console.log(this.$route.query.redirect);
            if (this.$route.query.redirect) {
              const redirect = this.$route.query.redirect;
              //   跳转到进入登录页前的路由
              this.$router.replace(redirect);
            } else {
              //   跳转至首页
              this.$router.replace("/");
            }
          } else if (res.status == 500) {
            this.message = "用户登录失败";
          } else if (res.status == 400) {
            this.message = "用户名或者密码错误";
          }
        })
        .catch((err) => {
          console.log(err.message);
        });
    },
  },
};
</script>

<style>
.user_box {
  width: 100%;
  height: 100%;
  background: darkgray;
}

.user_login {
  width: 210px;
  margin: 0 auto;
}

.user_login input {
  width: 100%;
  height: 30px;
  margin: 10px 0;
}

.user_login .submit {
  margin: 0 auto;
  width: 205px;
}

.user_login .submit input {
  width: 205px;
  height: 30px;
}
</style>
